package com.xhwl.centiotdata.suppliersystem.dahua;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.DaHuaConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.IdentityDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.PedestrianRecordDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.UserDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.pedestrian.DoorActionEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/03/ 09:44
 */
@Service
public class PedestrianDaHuaHandler {
    private static final Logger log = LoggerFactory.getLogger(GeneralDaHuaHandler.class);

    @Autowired
    private GeneralDaHuaHandler generalDaHuaHandler;

    public List<PedestrianRecordDaHuaDTO> pullRecord(PedestrianIntegrationConfigDTO configDTO) {
        List<PedestrianRecordDaHuaDTO> recordDaHuaDTOList = new ArrayList<>();
        Integer pageNum = 1;
        List<PedestrianRecordDaHuaDTO> recordList = null;
        do {
            recordList = this.requestRecord(pageNum, configDTO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            recordDaHuaDTOList.addAll(recordList);
            ++pageNum;
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);
        return recordDaHuaDTOList;
    }

    private List<PedestrianRecordDaHuaDTO> requestRecord(Integer pageNum, PedestrianIntegrationConfigDTO configDTO) {
        HashMap<String, Object> params = new HashMap<>(2);
        params.put("pageNum", pageNum);
        params.put("pageSize", 500);
        log.info("开始获取大华人行数据");
        // 时间范围：1~10；11~20；21~30；31~40；41~50；51~00
        params.put("startSwingTime", getIntervalSeconds(null, -9));
        params.put("endSwingTime", getIntervalSeconds(null, 0));
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.PEDESTRIAN_RECORD_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        log.info("获取大华人行数据结果:"+resultObject);
        log.info("获取大华人行数据结果:"+resultObject.getString("data"));
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.PEDESTRIAN_RECORD_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String data = resultObject.getString("data");
        JSONObject dataObject = JSON.parseObject(data);
        String pageDataStr = dataObject.getString("pageData");
        if (StringUtils.isEmpty(pageDataStr)) {
            log.error("post path:{};params:{};pageData is null!", DaHuaConstant.PEDESTRIAN_RECORD_URL, JSON.toJSONString(params));
            return null;
        }
        List<PedestrianRecordDaHuaDTO> recordList = JSONObject.parseArray(pageDataStr, PedestrianRecordDaHuaDTO.class);
        return recordList;
    }

    public ResultJson openDoor(PedestrianIntegrationConfigDTO configDTO, DeviceDTO deviceDTO, DoorActionEnum doorAction) {
        String api;
        switch (doorAction) {
            case REMOTELY_OPEN:
                api = DaHuaConstant.OPEN_DOOR;
                break;
            default:
                return ResultJson.fail("无对应设备操作");
        }
        HashMap<String, Object> params = new HashMap<>(1);
        params.put("channelCodeList", Arrays.asList(deviceDTO.getThirdDeviceId()));
        JSONObject resultObject = generalDaHuaHandler.post(api, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success();
    }

    public String getIntervalMinutes(Date date, int interval) {
        Calendar calendar = Calendar.getInstance();
        if (date == null) {
            calendar.setTime(new Date());
        } else {
            calendar.setTime(date);
        }
        calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE)) / 10 * 10);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.MINUTE, interval);
        Date resultDate = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(resultDate);
    }

    public String getIntervalSeconds(Date date, int interval) {
        Calendar calendar = Calendar.getInstance();
        if (date == null) {
            calendar.setTime(new Date());
        } else {
            calendar.setTime(date);
        }
        calendar.set(Calendar.SECOND, (calendar.get(Calendar.SECOND)) / 10 * 10);
        calendar.add(Calendar.SECOND, interval);
        Date resultDate = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(resultDate);
    }

    public Long createIdentity(PedestrianIntegrationConfigDTO configDTO) {
        IdentityDaHuaDTO identityDaHuaDTO = IdentityDaHuaDTO.builder().name("普通员工").description("默认身份").build();
        Map<String,Object> params = JSONObject.parseObject(JSONObject.toJSONString(identityDaHuaDTO), Map.class);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.CREATE_IDENTITY_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.CREATE_IDENTITY_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
        return resultObject.getLong("data");
    }

    public AuthAccountMapping createUser(PedestrianIntegrationConfigDTO configDTO, UserDaHuaDTO userDaHuaDTO) {
        Map<String,Object> params = JSONObject.parseObject(JSONObject.toJSONString(userDaHuaDTO), Map.class);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.CREATE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.CREATE_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
        AuthAccountMapping authAccountMapping = new AuthAccountMapping();
        String data = resultObject.getString("data");
        authAccountMapping.setOpenId(data);
        authAccountMapping.setOpenCode(userDaHuaDTO.getCode());
        return authAccountMapping;
    }

    public List queryIdentity(PedestrianIntegrationConfigDTO configDTO) {
        JSONObject resultObject = generalDaHuaHandler.get(DaHuaConstant.QUERY_IDENTITY_URL, null, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};errMsg:{}", DaHuaConstant.QUERY_IDENTITY_URL, resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }

        return resultObject.getObject("data",List.class);
    }

    public AuthAccountMapping queryUser(String phone, PedestrianIntegrationConfigDTO configDTO) {
        AuthAccountMapping authAccountMapping = null;
        HashMap<String, Object> params = new HashMap<>();
        params.put("phone",phone);
        params.put("pageNum",1);
        params.put("pageSize",10);
        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.QUERY_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.QUERY_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
        JSONObject data = resultObject.getJSONObject("data");
        JSONArray pageData = data.getJSONArray("pageData");
        if(!pageData.isEmpty()){
            JSONObject object = (JSONObject) pageData.get(0);
            UserDaHuaDTO userDaHuaDTO = object.toJavaObject(UserDaHuaDTO.class);
            authAccountMapping = new AuthAccountMapping();
            authAccountMapping.setOpenId(userDaHuaDTO.getId());
            authAccountMapping.setOpenCode(userDaHuaDTO.getCode());
        }
        return authAccountMapping;

    }

}
